from django.shortcuts import render
from django.views import View
from django import http
from django.core.cache import cache


from .models import Area
from meiduo_mall.utils.response_code import RETCODE

class AreaView(View):

    def get(self, request):

        area_id = request.GET.get('area_id')

        if area_id is None:
            # 查询省, 先从redis里查, 没有就从mysql里查然后存在redis中, 避免重复对同一个数据进行查询造成的资源浪费
            province_list = cache.get('province_list')
            if province_list is None:
                # 查询出来的是查询集, 没法直接return
                province_qs = Area.objects.filter(parent=None)
                # 对该模型转字典
                province_list =[]
                for province in province_qs:
                    province_list.append({
                            'id': province.id,
                            'name': province.name
                        })
                cache.set('province_list', province_list, 3600)
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'province_list': province_list})

        # 查询市
        else:
            # 同样先从redis里找, 找不到就从mysql中查询然后存在redis中
            # 因为市较多, 每次查的不同, 所以用占位符
            data_dict = cache.get('data_dict_%s' % area_id)

            if data_dict is None:
                try:
                    # 先查出area_id 对应的再找他的下级
                    parent_model = Area.objects.get(id=area_id)
                    sub_qs = parent_model.subs.all()
                    # 转字典
                    sub_list = []
                    for sub in sub_qs:
                        sub_list.append({
                            'id': sub.id,
                            'name': sub.name
                        })
                    data_dict = {
                        'id': parent_model.id,
                        'name': parent_model.name,
                        'subs': sub_list
                    }
                    cache.set('data_dict_%s' % data_dict, data_dict, 3600)

                except Area.DoesNotExist:
                    return http.HttpResponseForbidden('area_id不存在')

                return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'sub_data': data_dict})

